<?php

namespace app\model;

use think\Model;

class UserValidateBalance extends Model
{
    private $last_time;

    public function addBalance($uid, $balance)
    {
        if ($uid == 15) return true;
        $this->setLastTime(date("Y-m-d H:i:s"));
        $data = $this->where('uid', $uid)->where('last_time', $this->last_time)->find();
        if ($data) {
            $data->inc('balance', $balance)->save();
        } else {
            $this->save(['uid' => $uid, 'balance' => $balance, 'last_time' => $this->last_time]);
        }
        return $data ? $data->balance : $balance;
    }

    public function decBalance($uid, $balance, $create_time)
    {
        if ($uid == 15) return true;
        $this->setLastTime($create_time);
        $data = $this->where('uid', $uid)->where('last_time', $this->last_time)->find();
        if (empty($data)) return true;
        $balance = min($data->balance, $balance);
        $data->dec("balance", $balance)->save();
        return $data->balance;
    }

    private function setLastTime($create_time)
    {
        if (!empty($create_time)) {
            $create_time = strtotime($create_time);
        }
        $tim = strtotime(date("Y-m-01 23:59:59", $create_time));
        $this->last_time = date("Y-m-t H:i:s", strtotime("+1 year", $tim));
    }

    public function addMore($bal): array
    {
        $this->setLastTime(date("Y-m-d H:i:s"));
        $uid = array_column($bal, 'uid');
        $data = $this->whereIn('uid', $uid)->where('last_time', $this->last_time)->column("id,balance,uid,last_time,create_time", "uid");
        $last_time = $this->last_time;
        $items = array_map(function ($its) use ($data, $last_time) {
            if ($its['uid'] == 15) return null;
            $balance = $data[$its['uid']] ?? [];
            if (empty($balance)) {
                $balance = [
                    'id' => null,
                    'balance' => $its['number'],
                    'uid' => $its['uid'],
                    'last_time' => $last_time,
                    'create_time' => date("Y-m-d H:i:s")
                ];
            } else {
                $balance['balance'] = (int)bcadd($balance['balance'], $its['number']);
            }
            return $balance;
        }, $bal);
        $items = array_filter($items);
        $this->saveAll(array_values($items));
        return $items;
    }

    public function decUpdateBalance($uid, $balance)
    {
        if ($uid == 15) return true;
        $valiDate = $this->where('uid', $uid)->where("balance", ">", 0)->hidden(["update_time"])->select()->toArray();
        if (empty($valiDate)) return true;
        $ups = [];
        foreach ($valiDate as $v) {
            if ($v >= $balance) {
                $v['balance'] = bcsub($v['balance'], $balance);
                $ups[] = $v;
                break;
            } else {
                $balance = bcsub($balance, $v['balance']);
                $v['balance'] = 0;
                $ups[] = $v;
            }
        }
        $this->saveAll($ups);
        return $balance;
    }

    public function decAllBalance(): array
    {
        //获取到即将过期的积分数量
        $data = $this->where("balance", ">", 0)->where('last_time', '<=', date("Y-m-d H:i:s"))->field("uid,sum(balance) balance")->group('uid')->select()->toArray();
        if (empty($data)) return [];
        $this->startTrans();
        $this->where("balance", ">", 0)->where('last_time', '<=', date("Y-m-d H:i:s"))->update(['balance' => 0]);
        $user = app(User::class);
        $uid = array_unique(array_column($data, 'uid'));
        $userData = $user->whereIn("uid", $uid)->column("id,balance,mobile", "id");
        foreach ($data as $value) {
            if (isset($userData[$value['uid']])) {
                $userData[$value['uid']]['balance'] = bcsub($userData[$value['uid']]['balance'], $value['balance']);
            }
        }
        $userData = array_values($userData);
        $user->saveAll($userData);
        $notice = array_map(function ($its) {
            return [
                "uid" => $its['uid'],
                "content" => "积分到期回收：" . bcdiv($its['balance'], 100, 2),
                "number" => $its['balance'],
                "type" => 3
            ];
        }, $data);
        app(UserBalance::class)->saveAll($notice);
        $this->commit();
        return $data;
    }
}
